﻿using GatewayClient.Models;
using GatewayClient.Device;
using GatewayClient.MQ;
using Iot.Device.Pn532;
using IotDeviceToolHepler;

using IotDeviceToolHepler.Model.Device;
using Models.Common;
using Models.Constant;
using Models.Device;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UtilsBase;
using UtilsCache;
using static Models.Common.EnumDeviceState;

namespace GatewayClient.Service
{
    /// <summary>
    /// 处理指令
    /// </summary>
    public class ServiceHandleCommand
    {

        /// <summary>
        /// 判断执行次数
        /// </summary>
        /// <param name="obj"></param>
        public void handle(MQReqModel<object> mQReqModel)
        {
            CommandLogModel commandLogModel = mQReqModel.toGatewayData;
            if (commandLogModel.repeatCount == -100)
            {

                Console.WriteLine("############################################################");
                Console.WriteLine("关闭任务： " + commandLogModel.key + ".....设备：" + commandLogModel.device_remark);
                Console.WriteLine("############################################################");

                //停止
                UtilMemoryCacheHelper.remove("handleEvent" + commandLogModel.d_guid + commandLogModel.key + "-1");
                //回传成功
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.respMsg = ResponseCode.SUCCESS_MSG;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                return;
            }
            else
            {
                ////判断执行次数，用于传感器，连续上传

                ModelHandleEvent handleEvent = new ModelHandleEvent();
                handleEvent.guid = commandLogModel.guid;
                handleEvent.d_guid = commandLogModel.d_guid;
                handleEvent.repeatCount = commandLogModel.repeatCount;
                handleEvent.key = commandLogModel.key;
                handleEvent.runcount = 0;


                //处理内容
                try
                {
                    ModelHandleEvent events = UtilMemoryCacheHelper.get<ModelHandleEvent>("handleEvent" + commandLogModel.d_guid + commandLogModel.key + commandLogModel.repeatCount.ToString());
                    if (events != null)
                    {
                        //如果是回调rs485，停止回调的话，不会删除这个缓存，如果不允许相同指令重复执行，执回调将不再进行，所以这里 更新缓存，旧缓存任务停止运行
                        UtilMemoryCacheHelper.remove("handleEvent" + commandLogModel.d_guid + commandLogModel.key + commandLogModel.repeatCount.ToString());
                    }
                    // events = new List<ModelHandleEvent>();
                    // events.Add(handleEvent);
                    UtilMemoryCacheHelper.set("handleEvent" + commandLogModel.d_guid + commandLogModel.key + commandLogModel.repeatCount.ToString(), handleEvent);

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                Thread.Sleep(5);
            }
           // mQReqModel.respMsg = mQReqModel.respMsg + "," + DateTime.Now.ToString("HH:mm:ss.fff");
            handleTaskRun(commandLogModel, mQReqModel);

        }

        /// <summary>
        /// 处理指令任务，多线程，运行多个作业任务
        /// </summary>
        /// <param name="commandLogModel"></param>
        /// <param name="mQReqModel"></param>
        public void handleTaskRun(CommandLogModel commandLogModel, MQReqModel<object> mQReqModel)
        {
            int runcount = 0;

            while (true)
            {
                try
                {
                    ModelHandleEvent events = UtilMemoryCacheHelper.get<ModelHandleEvent>("handleEvent" + commandLogModel.d_guid + commandLogModel.key + commandLogModel.repeatCount.ToString());
                    if (events == null )
                    {
                        break;
                    }
                  
                    runcount = runcount + 1;
                    Console.WriteLine("############################################################");
                    Console.WriteLine("开始执行任务 " + commandLogModel.key + ".....设备" + commandLogModel.device_remark + " .....第:" + runcount + "次执行---设置的次数：" + commandLogModel.repeatCount);
                    Console.WriteLine("############################################################");


                    handleTaskRun_action(mQReqModel);//执行, 不能用新线程
                    if (commandLogModel.repeatCount != -1 && runcount >= commandLogModel.repeatCount)
                    {//如果非-1无限次数，判断执行次数，并退出

                        try
                        {
                            //处理内容

                            UtilMemoryCacheHelper.remove("handleEvent" + commandLogModel.d_guid + commandLogModel.key + commandLogModel.repeatCount.ToString());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                        break;
                    }
                    if (commandLogModel.repeatCountInterval > 0)
                    {//设置心跳时间
                        Thread.Sleep(commandLogModel.repeatCountInterval);
                    }
                    else
                    {                    //默认10秒
                        Thread.Sleep(10000);
                    }
                }
                catch (Exception ex)
                {
                    //UtilMemoryCacheHelper.remove("handleEvent" + commandLogModel.d_guid + commandLogModel.key + commandLogModel.repeatCount.ToString());
                    //  new UtilsFileHelper().log_WriteMessageAppend("handleTaskRunerror", "指令运行报错： " + commandLogModel.key + ".....设备：" + commandLogModel.device_remark + "-" + ex.ToString());
                    Console.WriteLine("异常退出任务:" + commandLogModel.d_guid + commandLogModel.key + "  handleTaskRun" + ex.ToString());
                    break;
                }
            }
        }



        public void handleTaskRun_action(MQReqModel<object> mQReqModel)
        {
            try
            {
                CommandLogModel item = mQReqModel.toGatewayData;
                if (item.deviceModelCode == "1001")
                {
                    //gpio处理
                    //获得能力，开始推送数据
                    new ServiceDeviceGpio().gateWayExecuteCommand(mQReqModel);
                }
                else if (item.deviceModelCode == "1004")
                {
                    //Console.WriteLine(".....获得能力Sht30_I2C.....");
                    //获得能力，开始推送数据
                    new ServiceDeviceSensorSHT301004().gateWayExecuteCommand(mQReqModel);
                }
                else if (item.agreementType == EnumAgreementType.RS485)
                {
                    //Console.WriteLine(".....RS485.....");
                    new ServiceHandleRS485().gateWayExecuteRS485(mQReqModel);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }


    }

}
